import 'dart:ui';

import 'package:airbnb_clone/internal/http/dao/article_view_dao.dart';

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

import '../../../components/dialog/msg_dialog.dart';
import '../../../constant/constant.dart';
import '../../../models/article.dart';
import '../../../models/response.dart';

// import '../shared/colors.dart';
// import '../widgets/property_type_list.dart';
// import '../widgets/app_nav_bar.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final List<Article> _articleList = [];
  final ScrollController _scrollController = ScrollController();
  int _page = 0;
  @override
  void initState() {
    super.initState();
    addPageListener();
    _loadData();
  }

  void addPageListener() {
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        setState(() {
          setState(() {
            _page++;
            _loadData();
          });
        });
      }
      if (_scrollController.position.pixels ==
          _scrollController.position.minScrollExtent) {
        // print("scroll to top");
        setState(() {});
      }
    });
  }

  Future<void> _loadData() async {
    TiebaResponse response = await ArticleViewDao.get(page: _page);
    if (response.code == 200) {
      // for (var i = 0; i < response.result['list'].length; i++) {
      //   print(response.result['list'][i]);
      //   _articleList.add(Article(id: response.result['list'][i], author: author, title: title, context: context, view: view, belong: belong, belongIconUrl: belongIconUrl, createTime: createTime, imgUrls: imgUrls))
      // }
      for (var article in response.result['list']) {
        _articleList.add(Article(
            id: article["id"],
            author: article["user_name"],
            authorId: article["user_id"],
            title: article["title"],
            context: article["article_context"],
            view: 400,
            belong: article["belong"],
            belongIconUrl: "https://t.mwm.moe/pc/",
            createTime: DateTime.parse(article["create_time"]),
            imgUrls: [
              "https://t.mwm.moe/pc/",
              "https://t.mwm.moe/pc/",
              "https://t.mwm.moe/pc/",
              "https://t.mwm.moe/pc/"
            ]));
      }
      if (mounted) {
        setState(() {});
      }
    } else {
      // ignore: use_build_context_synchronously
      MsgDialog.msgDialog(context, response.msg);
    }
  }

  @override
  Widget build(BuildContext context) {
    // final textTheme = Theme.of(context).textTheme;
    final size = MediaQuery.sizeOf(context);

    return SizedBox(
        height: size.height,
        child: Stack(
          children: [
            SizedBox(
                height: size.height * 0.13, child: articleSreachInput(context)),
            Positioned.fill(
                top: size.height * 0.13,
                child: SingleChildScrollView(
                  child: Container(
                    height: size.height * 0.87,
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: bgGradientColor,
                      ),
                    ),
                    padding: const EdgeInsets.symmetric(horizontal: 20),
                    child: _loadListData(_articleList, context),
                  ),
                ))
          ],
        ));
  }

  ListView _loadListData(List<Article> articleList, BuildContext context) {
    final size = MediaQuery.sizeOf(context);
    TextStyle titleStyle =
        const TextStyle(fontSize: 20, fontWeight: FontWeight.w400);
    TextStyle contextStyle = const TextStyle(color: Colors.grey);
    TextStyle authorStyle =
        const TextStyle(fontSize: 15, fontWeight: FontWeight.w300);
    return ListView.builder(
        controller: _scrollController,
        padding: const EdgeInsets.only(top: 10),
        itemCount: articleList.length,
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {
              // 路由跳转
              context.pushNamed("article",
                  pathParameters: {"id": "${articleList[index].id}"});
            },
            child: Container(
              padding: const EdgeInsets.all(14),
              margin: const EdgeInsets.only(top: 10),
              height: size.height * 0.35,
              width: size.width,
              decoration: BoxDecoration(
                  color: Colors.white, borderRadius: BorderRadius.circular(14)),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 文章归属
                  SizedBox(
                    height: 100,
                    child: Row(
                      children: [
                        Container(
                          width: 100,
                          height: 100,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(8),
                            child: Image.network(
                              articleList[index].belongIconUrl,
                              errorBuilder: (context, error, stackTrace) {
                                return Image.asset(
                                    "assets/images/netError.jpg");
                              },
                            ),
                          ),
                        ),
                        const SizedBox(
                          width: 20,
                        ),
                        SizedBox(
                          width: 150,
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                articleList[index].title,
                                style: titleStyle,
                                maxLines: 1,
                              ),
                              Text(
                                articleList[index].title,
                                style: authorStyle,
                                maxLines: 1,
                              ),
                              Text(
                                articleList[index].context,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: contextStyle,
                              )
                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                  // 图片列表
                  Container(
                    margin: const EdgeInsets.only(top: 10),
                    height: 100,
                    // decoration: BoxDecoration(color: Colors.amber),
                    child: ListView.builder(
                      scrollDirection: Axis.horizontal,
                      itemCount: articleList[index].imgUrls.length,
                      itemBuilder: (BuildContext context, int imgIndex) {
                        return Container(
                            margin: const EdgeInsets.only(right: 10),
                            width: 100,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(8)),
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(8),
                              child: Image.network(
                                articleList[index].imgUrls[imgIndex],
                                fit: BoxFit.cover,
                                errorBuilder: (context, error, stackTrace) {
                                  return Image.asset(
                                      "assets/images/netError.jpg");
                                },
                              ),
                            ));
                      },
                    ),
                  ),
                  // 底下状态栏
                  Expanded(
                      child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Row(children: [
                        Icon(Icons.share),
                        SizedBox(
                          width: 5,
                        ),
                        Text("分享")
                      ]),
                      const Row(children: [
                        Icon(Icons.comment),
                        SizedBox(
                          width: 5,
                        ),
                        Text("留言")
                      ]),
                      Row(children: [
                        const Icon(Icons.remove_red_eye_sharp),
                        const SizedBox(
                          width: 5,
                        ),
                        Text("${articleList[index].view}")
                      ])
                    ],
                  ))
                ],
              ),
            ),
          );
        });
  }
}

SizedBox articleSreachInput(BuildContext context) {
  return SizedBox(
    height: 70,
    child: Stack(
      children: [
        ClipRect(
          child: BackdropFilter(
              filter: ImageFilter.blur(sigmaX: 40, sigmaY: 40),
              child: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: topBarBgColor,
                  ),
                ),
              )),
        ),
        Positioned(
          left: 16.0,
          right: 50.0,
          top: 50.0,
          child: GestureDetector(
            onTap: () => context.pushNamed('booking-details'),
            child: Hero(
              tag: 'planning',
              child: Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 16.0,
                  vertical: 8.0,
                ),
                decoration: BoxDecoration(
                  color: appWhite,
                  border: Border.all(color: appGrey, width: 1.0),
                  borderRadius: BorderRadius.circular(32.0),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.4),
                      blurRadius: 4.0,
                      spreadRadius: 0.0,
                      offset: const Offset(3, 3),
                    )
                  ],
                ),
                child: Row(
                  children: [
                    const Icon(Icons.search),
                    const SizedBox(width: 8.0),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'Search Artcle',
                          style: Theme.of(context)
                              .textTheme
                              .bodyMedium!
                              .copyWith(fontWeight: FontWeight.bold),
                        ),
                      ],
                    )
                  ],
                ),
              ),
            ),
          ),
        ),
      ],
    ),
  );
}
